import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';
import { TypeOrmCrudService } from '@nestjsx/crud-typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { hashPassword } from '../common/utils/hash';

@Injectable()
export class UserService extends TypeOrmCrudService<User> {

  constructor(@InjectRepository(User) repo) {
    super(repo);
  }

  async register(user: CreateUserDto) {
    const u = new User;
    u.username = user.username
    u.password = await hashPassword(u.username)
    return await this.repo.save(u);
  }

  async changePassword(username: string, password: string): Promise<boolean> {
    const newPassword = await hashPassword(password);
    const result = await this.repo.update({ username }, { password: newPassword });
    return result.raw.changedRows > 0;
  }
}
